package com.spring.service.user;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.spring.domain.User;
import com.spring.service.util.UserMapper;

public class JdbcUserDao extends SimpleJdbcDaoSupport implements UserDao {
	protected final Log logger = LogFactory.getLog(getClass());
	
	public void deleteUser(List<User> users) {
		String idList="";
		for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
			User user = (User) iterator.next();
			idList+=user.getId();
			if (iterator.hasNext())idList+=",";
		}
		
		int count = getSimpleJdbcTemplate()
				.update("delete from user where id in ("+idList+")");
		logger.info("Rows affected: " + count);
	}
	
	public List<User> getUsers() {
		return getSimpleJdbcTemplate().query( "select id, mail, pwd, startDate, activationCode, newsLetter, admin from user", new UserMapper());
	}

	public int insertUser(User user) {
		logger.info("Saving user: " + user.getMail());
		int count = getSimpleJdbcTemplate()
				.update("insert user (mail, pwd, startDate, activationCode, newsLetter, admin) values (:mail, :pwd, :startDate, :activationCode, :newsLetter, :admin )",
						UserMapper.sqlMap(user));
		
		logger.info("Rows affected: " + count);
		
		return getJdbcTemplate().queryForInt( "select last_insert_id()" );
	

	}
	
	
	public User selectById(int id) {
		return (getSimpleJdbcTemplate().query( "select id, mail, pwd, startDate, activationCode, newsLetter, admin from user where id="+id, new UserMapper())).get(0);
	}
	
	
	public List<User> selectByMail(User user) {
		return getSimpleJdbcTemplate().query( "select id, mail, pwd, startDate, activationCode, newsLetter, admin from user where mail='"+user.getMail()+"'", new UserMapper());
	}

	
	public void updateUser(User user) {
		logger.info("Update user: " + user.getMail());
		int count = getSimpleJdbcTemplate()
				.update("update user set mail=:mail, pwd=:pwd, activationCode=:activationCode, newsLetter=:newsLetter, startDate=:startDate where id=:id",
						UserMapper.sqlMap(user));
		logger.info("Rows affected: " + count);

	}

	public User login(String userName, String pwd) {
		logger.info("login for user: " + userName +", pwd:"+pwd);
		
		List<User> usersFounded = getSimpleJdbcTemplate().query( "select id, mail, pwd, startDate, activationCode, newsLetter, admin from user where mail='"+userName+"' and pwd='"+pwd+"'", new UserMapper());
		if(CollectionUtils.isEmpty(usersFounded)){
			return null;
		}
		return usersFounded.get(0);	
	}
	
}
